package zhihui.mobile.ui.shop.details;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.IconHintView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.zgm.utils.DensityUtil;
import com.zgm.utils.ui.UiHeaderLayout;

import org.xutils.x;

import java.util.List;
import java.util.Map;

import cn.lankton.flowlayout.FlowLayout;
import zhihui.mobile.R;
import zhihui.mobile.bean.address.Province;
import zhihui.mobile.bean.shop.BannerInfo;
import zhihui.mobile.bean.shop.detail.ActivityInfo;
import zhihui.mobile.bean.shop.detail.Parameter;
import zhihui.mobile.bean.shop.detail.ShopDetail;
import zhihui.mobile.bean.shop.detail.SpecifInfo;
import zhihui.mobile.bean.shop.detail.SpuDetailInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.constants.ActivitySourceTag;
import zhihui.mobile.interfaces.share.IShareListener;
import zhihui.mobile.presenter.IPresenter;
import zhihui.mobile.presenter.share.SharePresenter;
import zhihui.mobile.presenter.shop.ShopDetailsPresenter;
import zhihui.mobile.ui.BaseActivity;
import zhihui.mobile.ui.shop.BannerAdapter;
import zhihui.mobile.ui.shop.order.ShopOrderConfirmActivity;
import zhihui.mobile.ui.shop.order.ShopOrderDetailsActivity;
import zhihui.mobile.ui.utils.UiUtils;

/**
 * Created by 张公铭 on 2017/8/4 0004.
 */
public class ShopDetailsActivity extends BaseActivity implements IShopDetailsContract.IShopDetailsView
{
    private ShopDetailsPresenter detailsPresenter = new ShopDetailsPresenter();
    private SharePresenter sharePresenter = null;
    private SpuDetailInfo spuDetailInfo;
    private Bitmap spuImg = null;

    private UiHeaderLayout mHeader;
    private PullToRefreshScrollView sv_content;
    private RollPagerView pv_banner;
    private RelativeLayout rl_sales;
    private TextView tv_sales_price;
    private TextView tv_sales_original_price;
    private TextView tv_sales_progress;
    private TextView tv_sales_time;
    private TextView tv_name;
    private LinearLayout ly_price;
    private TextView tv_price;
    private LinearLayout ll_activity;
    private RelativeLayout rl_specification;
    private TextView tv_specification_name;
    private TextView tv_specification_desc;
    private RelativeLayout rl_address;
    private TextView tv_address;
    private LinearLayout ll_parameter;
    private WebView wv_details;
    private RelativeLayout rl_footer_collect;
    private ImageView iv_collect;
    private TextView tv_collect;
    private RelativeLayout rl_footer_service;
    private TextView tv_footer_add_cart;
    private TextView tv_footer_buy;
    private BannerAdapter bannerAdapter;

    private int skuId = -1;
    private int num = 1;

    @Override
    public void initView()
    {
        sharePresenter = new SharePresenter(this);
        mHeader = (UiHeaderLayout) findViewById(R.id.header_shop_details);
        mHeader.setRootBackgroundColor("#fafafa");
        mHeader.setTitle("商品详情");
        mHeader.setTitleColor("#333333");
        mHeader.setLeftBottonIcon(R.drawable.shop_back);
        mHeader.setLeftButtonOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                goBack(ShopDetailsActivity.class);
            }
        });
        mHeader.setRightOneBottonIcon(R.drawable.share);
        mHeader.setRightOneButtonOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //分享
                UiUtils.showShareDialog(ShopDetailsActivity.this, new IShareListener()
                {
                    @Override
                    public void weixin()
                    {
                        sharePresenter.weixin(spuDetailInfo.getTitle(), spuDetailInfo.getTitle(), spuImg, "http//www.baidu.com", 0);
                    }

                    @Override
                    public void friend()
                    {
                        sharePresenter.weixin(spuDetailInfo.getTitle(), spuDetailInfo.getTitle(), spuImg, "http//www.baidu.com", 1);
                    }

                    @Override
                    public void qq()
                    {
                        sharePresenter.qq(spuDetailInfo.getTitle(), spuDetailInfo.getTitle(), Config.FILE_URL + spuDetailInfo.getSpuimg(), "", false);
                    }
                });
            }
        });

        mHeader.setRightTwoBottonIcon(R.drawable.black_cart);
        mHeader.setRightTwoButtonOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                detailsPresenter.goShopCart(ShopDetailsActivity.this, ShopDetailsActivity.this);
            }
        });

        sv_content = (PullToRefreshScrollView) findViewById(R.id.sv_shop_details_content);
        pv_banner = (RollPagerView) findViewById(R.id.pv_shop_details);
        pv_banner.setHintView(new IconHintView(this, R.drawable.tips_select, R.drawable.tips_normal, 20));
        bannerAdapter = new BannerAdapter(this);
        pv_banner.setAdapter(bannerAdapter);
        pv_banner.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(int position)
            {
                //大图片播放器
            }
        });

        rl_sales = (RelativeLayout) findViewById(R.id.rl_shop_details_sales);
        rl_sales.setVisibility(View.GONE);
        tv_sales_price = (TextView) findViewById(R.id.tv_shop_details_sales_price);
        tv_sales_original_price = (TextView) findViewById(R.id.tv_shop_details_sales_original_price);
        tv_sales_progress = (TextView) findViewById(R.id.tv_shop_details_sales_progress);
        tv_sales_time = (TextView) findViewById(R.id.tv_shop_details_sales_time);

        tv_name = (TextView) findViewById(R.id.tv_shop_details_name);
        ly_price = (LinearLayout) findViewById(R.id.ly_shop_details_price);
        tv_price = (TextView) findViewById(R.id.tv_shop_details_prices);

        ll_activity = (LinearLayout) findViewById(R.id.ll_shop_details_activity);

        rl_specification = (RelativeLayout) findViewById(R.id.rl_shop_details_specification);
//        rl_specification.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View v)
//            {
//                detailsPresenter.getSpecificationInfo(1);
//            }
//        });
        tv_specification_name = (TextView) findViewById(R.id.tv_shop_details_specification_name);
        tv_specification_desc = (TextView) findViewById(R.id.tv_shop_details_specification_desc);

        tv_address = (TextView) findViewById(R.id.tv_shop_details_address);

        ll_parameter = (LinearLayout) findViewById(R.id.ly_shop_details_parameter);
        wv_details = (WebView) findViewById(R.id.wv_shop_details);

        rl_footer_collect = (RelativeLayout) findViewById(R.id.rl_shop_details_collect);
        rl_footer_collect.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //收藏
                detailsPresenter.attention();

            }
        });
        iv_collect = (ImageView) findViewById(R.id.iv_shop_details_collect);
        tv_collect = (TextView) findViewById(R.id.tv_shop_detail_collect);
        rl_footer_service = (RelativeLayout) findViewById(R.id.rl_shop_details_service);
        rl_footer_service.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //服务
                com.zgm.utils.UiUtils.showDialog(ShopDetailsActivity.this, "客服电话", "tel:18511587927");
            }
        });
        tv_footer_add_cart = (TextView) findViewById(R.id.tv_shop_details_cart);
        tv_footer_add_cart.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (!zhihui.mobile.ui.utils.UiUtils.cheeckLogin(ShopDetailsActivity.this, ActivitySourceTag.ShopDetailsActivity))
                {
                    return;
                }
                detailsPresenter.addShopCart(skuId, 1);
            }
        });

        tv_footer_buy = (TextView) findViewById(R.id.tv_shop_details_buy);
        tv_footer_buy.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (!zhihui.mobile.ui.utils.UiUtils.cheeckLogin(ShopDetailsActivity.this, ActivitySourceTag.ShopDetailsActivity))
                {
                    return;
                }
                detailsPresenter.goComfirmOrder(skuId, num);
            }
        });
        detailsPresenter.initViewData();
    }

    @Override
    protected int getLayoutResId()
    {
        return R.layout.shop_details_ativity;
    }

    @Override
    protected IPresenter[] getPresenters()
    {
        return new IPresenter[]{detailsPresenter};
    }

    @Override
    protected void onInitPresenter()
    {
        detailsPresenter.init(this, this);
    }

    @Override
    public void refreshView(ShopDetail shopDetail)
    {
        spuDetailInfo = shopDetail.getSpu();
        spuImg = ImageLoader.getInstance().loadImageSync(Config.FILE_URL + spuDetailInfo.getSpuimg() + ",resize,20,20");
        if (shopDetail.getConcern() == 1)
        {
            iv_collect.setImageResource(R.drawable.collect_select);
            tv_collect.setText("已关注");
            rl_footer_collect.setEnabled(false);
        }
        tv_name.setText(shopDetail.getSpu().getTitle());
        tv_price.setText(((double) shopDetail.getSpu().getMinprice() / 100) + "~" + ((double) shopDetail.getSpu().getMaxprice() / 100));
        initParameter(shopDetail.getParameter());
        initAvtivities(shopDetail.getCoupon());
        wv_details.loadUrl(Config.SERVERS + "/html/spu/" + shopDetail.getSpu().getId());
        wv_details.setWebViewClient(new WebViewClient()
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                view.loadUrl(url);
                return true;
            }
        });
    }

    private void updateSpecificationDesc(String name, String value, int skuId, int num, int price)
    {
        tv_specification_name.setText(name);
        tv_specification_desc.setText(value);
        tv_price.setText("" + ((double) price / 100));
        this.skuId = skuId;
        this.num = num;
    }

    @Override
    public void refreshBanner(List<BannerInfo> list)
    {
        bannerAdapter.setmList(list);
        bannerAdapter.notifyDataSetChanged();
    }

    @Override
    public void showSpecificationDialog(Map<String, List<SpecifInfo>> map, final int type)
    {
        final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        final SpecifInfo curSpu = new SpecifInfo();
        View view = LayoutInflater.from(this).inflate(R.layout.shop_specification_dialog, null);
        final ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_specification_dialog_icon);
        final TextView tv_price = (TextView) view.findViewById(R.id.tv_specification_dialog_price);
        final TextView tv_name = (TextView) view.findViewById(R.id.tv_specification_dialog_name);
        ImageView iv_close = (ImageView) view.findViewById(R.id.iv_specification_dialog_close);
        iv_close.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialog.dismiss();
            }
        });
        final TextView tv_num = (TextView) view.findViewById(R.id.tv_specification_dialog_num);
        ImageView iv_add = (ImageView) view.findViewById(R.id.iv_specification_dialog_add);
        iv_add.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                int num = Integer.parseInt(tv_num.getText().toString());
                num += 1;
                tv_num.setText(num + "");
                ShopDetailsActivity.this.num = num;
            }
        });
        ImageView iv_subract = (ImageView) view.findViewById(R.id.iv_specification_dialog_subtract);
        iv_subract.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                int num = Integer.parseInt(tv_num.getText().toString());
                if (num > 1)
                {
                    num -= 1;
                    tv_num.setText(num + "");
                    ShopDetailsActivity.this.num = num;
                }
            }
        });

        TextView tv_add_cart = (TextView) view.findViewById(R.id.tv_specification_dialog_add_cart);
        if (type == 2)
        {
            tv_add_cart.setText("立即购买");
        }
        LinearLayout ll_specifications = (LinearLayout) view.findViewById(R.id.ll_specification_dialog_content);
        for (final String key : map.keySet())
        {
            View itemView = LayoutInflater.from(this).inflate(R.layout.shop_specification_item, ll_specifications, false);
            TextView tv_specification_name = (TextView) itemView.findViewById(R.id.tv_specification_item_name);
            tv_specification_name.setText(key);
            FlowLayout fl_content = (FlowLayout) itemView.findViewById(R.id.fl_specifaition_item_content);
            boolean isSelect = false;
            final TextView[] finalTv_last_select = new TextView[1];
            for (final SpecifInfo specifInfo : map.get(key))
            {
                final TextView tv_item = new TextView(this);
                tv_item.setText(specifInfo.getSepcifvalue());
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(DensityUtil.dip2px(this, 10), 0, DensityUtil.dip2px(this, 10), 0);
                tv_item.setLayoutParams(layoutParams);
                tv_item.setPadding(DensityUtil.dip2px(this, 15), DensityUtil.dip2px(this, 5), DensityUtil.dip2px(this, 15), DensityUtil.dip2px(this, 5));
                tv_item.setGravity(Gravity.CENTER);
                tv_item.setBackgroundResource(R.drawable.specification_item_normal);
                if (!isSelect)
                {
                    if (specifInfo.getSkuid() > -1)
                    {
                        tv_item.setBackgroundResource(R.drawable.specification_item_select);
                        ImageLoader.getInstance().displayImage(Config.FILE_URL + specifInfo.getThumbnail(), iv_icon);
                        tv_name.setText("商品编码：" + specifInfo.getSkucode());
                        tv_price.setText("￥" + ((double) specifInfo.getPrice() / 100));
                        curSpu.setSkuid(specifInfo.getSkuid());
                        updateSpecificationDesc(key, specifInfo.getSepcifvalue(), specifInfo.getSkuid(), Integer.parseInt(tv_num.getText().toString()), specifInfo.getPrice());
                        finalTv_last_select[0] = tv_item;
                        isSelect = true;
                    }
                }
                if (specifInfo.getSkuid() > -1)
                {
                    tv_item.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if (finalTv_last_select[0] != v)
                            {
                                curSpu.setSkuid(specifInfo.getSkuid());
                                ImageLoader.getInstance().displayImage(Config.FILE_URL + specifInfo.getThumbnail(), iv_icon);
                                tv_name.setText("商品编码：" + specifInfo.getSkucode());
                                tv_price.setText("￥" + ((double) specifInfo.getPrice() / 100));
                                tv_item.setBackgroundResource(R.drawable.specification_item_select);
                                finalTv_last_select[0].setBackgroundResource(R.drawable.specification_item_normal);
                                finalTv_last_select[0] = (TextView) v;
                                updateSpecificationDesc(key, specifInfo.getSepcifvalue(), specifInfo.getSkuid(), Integer.parseInt(tv_num.getText().toString()), specifInfo.getPrice());
                            }
                        }
                    });
                } else
                {
                    tv_item.setBackgroundResource(R.drawable.specification_item_enable);
                    tv_item.setEnabled(false);
                }
                fl_content.addView(tv_item);
            }

            if (isSelect)
            {
                tv_add_cart.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if (type == 1)
                        {
                            detailsPresenter.addShopCart(curSpu.getSkuid(), Integer.parseInt(tv_num.getText().toString()));
                        } else if (type == 2)
                        {
                            detailsPresenter.goComfirmOrder(curSpu.getSkuid(), Integer.parseInt(tv_num.getText().toString()));
                        }
                    }
                });
            }
            ll_specifications.addView(itemView);
        }
        //布局给Dialog
        dialog.setContentView(view);
        //获取当前Activity窗体
        Window window = dialog.getWindow();
        //设置dialog 从底部弹出
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得窗体属性
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.y = 0;
        window.setAttributes(params);
        dialog.show();
    }

    @Override
    public void goComfirmOrderActivity()
    {
        Intent intent = new Intent(this, ShopOrderConfirmActivity.class);
        startActivity(intent);
    }

    @Override
    public void refreshCartNum(int num)
    {
        mHeader.setRightTwoButtonNum(num);
    }

    @Override
    public void initSpecification(String key, String value, int skuId, int price)
    {
        tv_specification_name.setText(key);
        tv_specification_desc.setText(value);
        tv_price.setText("" + ((double) price / 100));
        this.skuId = skuId;
        this.num = 1;
    }

    @Override
    public void updateBuyState(int salestock)
    {
        if (salestock <= 0)
        {
            tv_footer_buy.setEnabled(false);
            tv_footer_buy.setText("已售罄");
            tv_footer_buy.setTextColor(Color.parseColor("#999999"));
            tv_footer_add_cart.setEnabled(false);
        }
    }

    /**
     * 初始化活动描述
     */
    private void initAvtivities(List<ActivityInfo> list)
    {
        if (list == null || list.size() == 0)
        {
            ll_activity.setVisibility(View.GONE);
            return;
        }
        ll_activity.setVisibility(View.VISIBLE);
        for (ActivityInfo activityInfo : list)
        {
            View view = LayoutInflater.from(this).inflate(R.layout.shop_detail_activity_item, ll_activity, false);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_shop_details_activity_item_icon);
            tv_name.setText(ActivityInfo.getTypeString(activityInfo.getType_f()));
            TextView tv_desc = (TextView) view.findViewById(R.id.tv_shop_details_activity_item_desc);
            tv_desc.setText(activityInfo.getDesc_f());

            ll_activity.addView(view);
        }
    }

    /**
     * 初始化商品参数
     */
    private void initParameter(List<Parameter> list)
    {
        if (list == null || list.size() == 0)
        {
            ll_parameter.setVisibility(View.GONE);
            return;
        }
        ll_parameter.setVisibility(View.VISIBLE);
        for (int i = 0; i < list.size(); i++)
        {
            final Parameter parameter = list.get(i);
            View itemView = LayoutInflater.from(this).inflate(R.layout.shop_details_parameter_item, ll_parameter, false);
            TextView tv_name = (TextView) itemView.findViewById(R.id.tv_shop_parameter_name);
            tv_name.setText(parameter.getName_f());
            TextView tv_value = (TextView) itemView.findViewById(R.id.tv_shop_parameter_values);
            tv_value.setText(parameter.getParameter_f());

            ll_parameter.addView(itemView);
        }
    }
}
